package com.abel.bigwater.dataserver.model.ewide

import com.abel.bigwater.data.BcdString
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import io.netty.buffer.Unpooled
import org.joda.time.DateTime
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.slf4j.LoggerFactory

class KmingUploadReqDataTest {

    @Test
    fun parseBuf() {
        val buf = Unpooled.buffer().apply {
            writeBytes(BcdString.toByteArray("802013073011145700"))
        }

        val r = KmingUploadReqData().apply {
            assertEquals(true, parseBuf(buf))

            assertEquals(DateTime(2013, 7, 30, 11, 14, 57).toDate(), backTime)
            assertEquals(SessionReponseType.Success, respondType)
        }
    }

    @Test
    fun pack() {
        val r = KmingUploadReqData().apply {
            backTime = DateTime(2013, 7, 30, 11, 14, 57).toDate()
            respondType = SessionReponseType.Success
        }

        val buf = Unpooled.buffer().apply {
            r.pack(this)

            assertEquals("802013073011145700", BcdString.hexString(this))
        }
    }

    @Test
    fun packWhole() {
        val p = KmingPacket().apply {
            termCode = TermCodeType().also {
                it.manuId = BcdString.fromBcdString("03")
                it.codeBcd = BcdString.fromBcdString("01000000")
            }

            deviceStatus = DeviceStatus().also {
                it.lowBattery10 = true
                it.magnet21 = true
                it.breakLine30 = true
            }

            frameNo = 1
            data = KmingUploadReqData().apply {
                backTime = DateTime(2013, 7, 30, 11, 14, 57).toDate()
                respondType = SessionReponseType.Success
            }
        }

        val buf = Unpooled.buffer().apply {
            p.pack(this)

            assertEquals("5A55010000000301020101000900802013073011145700EFD36A69", BcdString.hexString(this).toUpperCase())
        }
    }

    @Test
    fun parseWhole() {
        val buf = Unpooled.buffer().apply { writeBytes(BcdString.toByteArray("5A55010000000301020101000900802013073011145700EFD36A69")) }
        val p = KmingPacket()
        assertTrue(p.parseBuf(buf))

        lgr.info(JSON.toJSONStringWithDateFormat(p, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature.PrettyFormat))

        assertEquals(TermCodeType().apply {
            manuId = BcdString.fromBcdString("03")
            codeBcd = BcdString.fromBcdString("01000000")
        }, p.termCode)

        val data = p.data as KmingUploadReqData
        assertEquals(DateTime(2013, 7, 30, 11, 14, 57).toDate(), data.backTime)
        assertEquals(SessionReponseType.Success, data.respondType)
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(KmingUploadReqDataTest::class.java)
    }
}